package com.example.myapplication;

import com.example.myapplication.shortvideo.utils.GsonUtil;
import com.example.myapplication.shortvideo.utils.TextUtils;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * @author: rongfeng
 * @date: 2020/9/2
 * @description
 */
public class quword {
    static volatile int index = 0;

    public static List<String> words = new ArrayList<>();
    static ExecutorService pool;

    static volatile List<String> shibai = new ArrayList<>();

    public static void main(String[] args) {
        pool = Executors.newFixedThreadPool(3);
        List<String> list = new ArrayList<>(new ReadWords().start3());
        for (String item : list
        ) {
            if (item.contains("'") || item.contains("-") || item.contains(" ") || item.contains("(") || item.contains(")")) {

            } else {
                words.add(item);
            }
        }
        System.out.println(words.size());
        start();
    }

    public static void start() {
        for (int i = 0; i <3; i++) {
            nextClass();
        }
    }


    public synchronized static void nextClass() {
        pool.execute(new Runnable() {
            @Override
            public synchronized void run() {
                if (index < words.size()) {
                    String word = words.get(index);
                    String url = getUrl(word);
                    index++;
                    if (isExists(word)) {
                        Word wordBean = getBean(word);
                        if (wordBean != null && (wordBean.getCiyuan() == null || wordBean.getCiyuan().equals(""))) {
                            new Query2().getDns(url, word);
                        }else {
                            nextClass();
                        }
                    }
                }
            }
        });

        if (index == words.size()) {
            System.out.println("失败 " + shibai.size());
            for (String word :
                    shibai) {
                System.out.println(word);
            }

        }


    }

    public static String getUrl(String word) {
        return "https://www.quword.com/w/" + word;
    }


    public static class Query2 {
        public void getDns(String url, String word) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .build();
            final Request request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    shibai.add(word);
                }

                @Override
                public void onResponse(Call call, @NotNull okhttp3.Response response) throws IOException {
                    if (response.body() != null) {
                        String html = response.body().string();
                        String ciyuan = getCiyuan(html);
                        if (!ciyuan.equals("")) {
                            Word wordBean = getBean(word);
                            if (wordBean != null) {
                                wordBean.setCiyuan(ciyuan);
                                saveFile(wordBean, word);
                            }
                        }
                        nextClass();
                    }
                }
            });
        }
    }


    public static Word getBean(String word) {
        File file = new File("D:\\wrf\\qn3\\" + word + ".json");
        try {
            String str;
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer sb = new StringBuffer();
            String text = null;
            while ((text = bufferedReader.readLine()) != null) {
                sb.append(text);
            }
            str = sb.toString();

            Word bean = GsonUtil.parse(str, Word.class);

            fileInputStream.close();
            return bean;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getCiyuan(String html) {
        String tag1 = "<span class=\"ciyuan-title\">";
        int index1 = html.indexOf(tag1);
        if (index1 > 0) {
            String html1 = html.substring(index1 + tag1.length());
            String tag2 = "<p>";
            int index2 = html1.indexOf(tag2);
            if (index2 > 0) {
                String html2 = html1.substring(index2 + tag2.length());
                String tag3 = "</p>";
                int index3 = html2.indexOf(tag3);
                if (index3 > 0) {
                    String html3 = html2.substring(0, index3);
                    System.out.println(html3);
                    return html3;
                }
            }
        }
        return "";
    }


    public static boolean isExists(String word) {
        File file = new File("D:\\wrf\\qn3\\" + word + ".json");
        System.out.println("ssss " + index);

        return file.exists();
    }


    public static void saveFile(Word bean, String word) {
        File file = new File("D:\\wrf\\qn3\\" + word + ".json");
        try {
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            String json = GsonUtil.toJson(bean);
            BufferedWriter out = new BufferedWriter(new FileWriter(file));
            out.write(json);
            out.close();
        } catch (IOException e) {
            System.out.println(word);
            e.printStackTrace();
        }
    }


    public static class Wfs implements Serializable {
        private String name;

        private String value;

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return this.name;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getValue() {
            return this.value;
        }
    }

    public static class Trs implements Serializable {

        public Trs(String pos, String tran) {
            this.pos = pos;
            this.tran = tran;
        }

        private String pos;

        private String tran;

        public void setPos(String pos) {
            this.pos = pos;
        }

        public String getPos() {
            return this.pos;
        }

        public void setTran(String tran) {
            this.tran = tran;
        }

        public String getTran() {
            return this.tran;
        }
    }

    public static class Word implements Serializable {

        private String word;

        private String usphone;

        private String ukphone;

        private String ciyuan;

        private List<Trs> trs;

        private List<Wfs> wfs;

        public String getWord() {
            return word;
        }

        public void setWord(String word) {
            this.word = word;
        }

        public void setUsphone(String usphone) {
            this.usphone = usphone;
        }

        public String getUsphone() {
            return this.usphone;
        }

        public void setUkphone(String ukphone) {
            this.ukphone = ukphone;
        }

        public String getUkphone() {
            return this.ukphone;
        }


        public List<Trs> getTrs() {
            return trs;
        }

        public void setTrs(List<Trs> trs) {
            this.trs = trs;
        }

        public void setWfs(List<Wfs> wfs) {
            this.wfs = wfs;
        }

        public List<Wfs> getWfs() {
            return this.wfs;
        }

        public String getCiyuan() {
            return ciyuan;
        }

        public void setCiyuan(String ciyuan) {
            this.ciyuan = ciyuan;
        }
    }


}
